在瀏覽器上登入 MongoDB,然後點擊專案 Database 的 Search 功能,接著選擇「Create Search Index」

選擇「JSON Editor」格式


確認內容正確後,按下建立 Search Index

稍微等一下後就會看到建立好的 Search Index

點擊名稱「default」→「Search Tester」,可以直接測試功能是否正常

點擊右邊的「Edit Query Syntax」,可以看到以 mongoose 書寫的程式碼,接下來就是將這些加進我們的後端 API

searchPost APIreq.params.keyword
(.*)${keyword}(.*) ,這樣就能順利搜尋中文的內容啦!exports.searchPost = async (req, res, next) => {
    try {
        const { keyword } = req.params;
        const posts = await Post.aggregate([
            {
                $search: {
                    index: 'default',
                    text: {
                        query: `(.*)${keyword}(.*)`,
                        path: {
                            wildcard: '*',
                        },
                    },
                },
            },
        ]);
        res.status(200).json({
            status: 'success',
            data: {
                data: posts,
            },
        });
    } catch (err) {
        console.log(err);
        res.status(404).json({
            status: 'error',
        });
    }
};
記得要在 postRoutes.js 新增路徑
router.route('/searchPost/:keyword').get(postController.searchPost);
api/index 新增 searchPost()
App.js 新增路徑 /search 並建立 <Search /> 頁面Home.js 修改 handleSearch ,然後使用 useNavigate ,讓執行時會跳轉到 Search 頁面,並將 keyword 變數傳過去import { useNavigate } from 'react-router-dom';
const handleSearch = () => {
    if (keyword.length < 1) {
        alert('搜尋關鍵字:請輸入至少 1 個字');
        return;
    }
    navigate(`/search`, { state: { keyword } });
};
<input> 使用 onKeyPress 來判斷使用者在輸入搜尋關鍵字時按下 Enter 就會執行 handleSearch
<input
    type="text"
    placeholder={'關鍵字'}
    value={keyword}
    onChange={(e) => setKeyword(e.target.value)}
    onKeyPress={(e) => (e.key === 'Enter' ? handleSearch() : null)}
    className="absolute w-2/5 h-10 rounded-md pl-10 focus:outline-0 focus:bg-yellow-700/5"
></input>

Search.js 頁面Home.js 來修改useLocation 來取得從 Home.js 傳來的 keyword 變數,並設定為狀態變數 keyword 的初始值import { useLocation } from 'react-router-dom';
const location = useLocation();
const [keyword, setKeyword] = useState(location.state.keyword ? location.state.keyword : '');
searchPost ,並在 useEffect 及 handleSearch 中使用posts.length 判斷式,在找不到相關文章時提示使用者{posts.length !== 0 ? (
    <Post data={posts} />
) : (
    <div className="">沒有符合條件的文章,試試其他關鍵字?</div>
)}


頁面的呈現會像這樣子~ 這樣就大致完成搜尋文章的功能啦!


